import cv2
import requests
import threading
from AUTO_link import AUTOLinkReceiver




# 服务器URL
lunch_code = '1631'
id = str(0)
video_server_url = 'http://82.156.90.140:80/upload_video/'+ lunch_code + id
data_server_url = 'http://82.156.90.140:80/upload_data/'+ lunch_code + id
comd_server_url = 'http://82.156.90.140:80/get_comd_rst/'+ lunch_code + id
# 串口数据接收
port_serial = '/dev/ttyACM0'
baudrate = 115200
# 视频帧地址
cap_id = 0




def send_video_frame(capd = None):
    """
    capd: 视频源，可以是摄像头设备号或网络流地址
    发送视频帧到服务器
    """
    if capd is None:
        return
    # 打开摄像头
    cap = cv2.VideoCapture(capd)
    if not cap.isOpened():
        print("Error: Could not open camera.")
        return
    while True:
        ret, frame = cap.read()
        if not ret:
            print("Error: Could not read frame.")
            break
        # 将帧编码为JPEG格式
        _, img_encoded = cv2.imencode('.jpg', frame)
        # 将视频帧发送到服务器
        video_response = requests.post(video_server_url, files={'video': ('frame.jpg', img_encoded.tobytes(), 'image/jpeg')})
        if video_response.status_code == 200:
            print("Video frame sent successfully")
        else:
            print("Failed to send video frame")




def send_data_frame(msg=b"None"):
    """
    port: 数据源，可以是UDP端口号或串口设备路径
    host_baudrate_or_ip: 数据源的波特率或者UDP的IP地址(例如'192.168.1.100'或者115200)
    发送串口数据到服务器
    """
    # 将串口数据发送到服务器
    data_response = requests.post(data_server_url, data={'serial_data': msg})
    if data_response.status_code == 200:
        print("Serial data sent successfully")
    else:
        print("Failed to send serial data")
def send_data_frame_thread(msg=b"None"):
    """
    port: 数据源，可以是UDP端口号或串口设备路径
    host_baudrate_or_ip: 数据源的波特率或者UDP的IP地址(例如'192.168.1.100'或者115200)
    发送串口数据到服务器
    """
    threading.Thread(target=send_data_frame, args=(msg,)).start()




def download_command():
    response = requests.get(comd_server_url)
    if response.status_code == 200:
        data = response.json()
        hex_data = ""
        for i in data:
            hex_data = hex_data + i[1]
        # 将16进制字符串转换回字节数据
        byte_data = bytes.fromhex(hex_data)
        return byte_data
    else:
        return None





if __name__ == "__main__":
    # 视频帧发送上行链路
    threading.Thread(target=send_video_frame, args=(cap_id,)).start()
    # 串口数据接收上行链路
    receiver_serial = AUTOLinkReceiver(port_serial, send_data_frame_thread, host_baudrate_or_ip=baudrate)
    #receiver_serial.start_receiving()
    threading.Thread(target=receiver_serial.start_receiving).start()
    # 下载指令下行链路
    while True:
        comd_data = download_command()
        if comd_data is not None:
            print("loading", comd_data)
            receiver_serial.write(comd_data)
